mui.init();
var mask = mui.createMask(); //callback为用户点击蒙版时自动执行的回调；
function show() {
	mask.show(); //显示遮罩
}
layui.use('upload', function () {
	var upload = layui.upload;
	//获取一键报修的id
	var repairId = getUrlParam('id');
	var openId = $.cookie("openId")?$.cookie("openId"):"123";
	$.ajax({
        url: WX_SIGN_URL,
        data: { url: location.href.split('#')[0]},
        success: function (res) {
            wx.config({
                debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: res.appId, // 必填，公众号的唯一标识
                timestamp: res.timestamp, // 必填，生成签名的时间戳
                nonceStr: res.nonceStr, // 必填，生成签名的随机串
                signature: res.signature, // 必填，签名
                jsApiList: ['scanQRCode'] // 必填，需要使用的JS接口列表
            });
        }
    });
	var productImage = [];
	var productName = [];
	Server.getFromCustomer('/searchAllRegisterDataByCustomerId',{openId : openId}, function(result){
		if(result.code !== 101){
			layer.msg('暂无注册产品');
			return false;
		}
		var data = result.data.data;
		var repairData;
		
		//遍历产品，获取产品弹框数据
		for(var i in data){
			//如果产品Id=一键报修的产品id，则记住该产品，并赋值
			if((data[i].id+'') === repairId){
				repairData = data[i];
			}
			productImage.push("<img id='"+data[i].id+"' src='" + data[i].productImage + "' title='"+ data[i].serialNo +"' style='display:inline;height:32px'>" +data[i].productName);
			productName.push(data[i].productName);
		}
		// $("#showProductPicker").on('click',function(){
			$("#showProductPicker").picker({
				title: "选择产品",
				cols: [{
					textAlign: 'center',
					displayValues: productImage,
					values: productName
				}],
				onClose: function(result) {
					//保存选中产品的id
					$("#showProductPicker").attr('title',$('.picker-selected img')[0].id);
					
					$('input[name=customerName]').val(repairData.customerInfo.name);
					$('#serialNo').val($('.picker-selected img')[0].title);
					mask.close();
				},
			});
		// });
		//一键报修时，初始化产品数据和客户数据
		if(repairData){
			$('#showProductPicker').val(repairData.productName);
			$('#serialNo').val(repairData.serialNo);
			//发票如果不为空，则显示发票
			repairData.productImage ? $('#uploaderFiles').append('<li class="weui-uploader__file" data-index="0" style="background-image:url('+ repairData.productImage +')"></li>') : '';
			$('input[name=customerName]').val(repairData.customerInfo.name);
			$('input[name=customerTel]').val(repairData.customerInfo.tel);
		}
	});
	$("#city-picker").cityPicker({
		title: "请选择所在地",
		onClose: function(result) {
			mask.close();
		},
	});

	//初始化发票上传
	uploadInit('#uploadBill', '#uploaderFiles');

	//多图上传
	upload.render({
		elem: '#uploadpic',
		method: 'post',
		auto: false, //不自动上传
		multiple: true,
		choose: function (obj) {
			obj.preview(function (index, file, result) {
				var url = URL.createObjectURL(file);
				var curTiem = new Date().getTime();
				$("#picsPlace").append('<div class="zoomImage" style="background-image:url(' + url + ')" title="'+(curTiem + file.name)+'"></div>');
				var param = {
					file:file,
					success:function(err, data){
						if (err) {
							layer.msg('上传失败！');
							return;
						}
					},
					curTiem:curTiem
				};
				uploadToCos(param);
			});
		}
	});
	//	多视频上传
	var uploadInst = upload.render({
		elem: '#uploadVideo',
		method: 'post',
		accept: 'video', //视频类型
		exts:'mov|mp4',
		auto: false,
		multiple: true,
		choose: function (obj) { // 选择文件之后，提交文件之前，你想干什么？
			var loadIndex = layer.load(2);
			obj.preview(function (index, file, result) {
				// var curTiem = new Date().getTime();
				
				var url = URL.createObjectURL(file);
				if (url != null) { // 显示video标签，用于预览
					$('.video').css("display", "inline-block");
					$('#videoPlay1').attr('src', url); //预读本地文件示例，TODO 保存上传视频的 appId,fileId

					var videoDom = ['<div class="videoDiv">',
					'<video class="prev" id="'+ index +'" src="' + url + '" title="'+file.name+'" x-webkit-airplay="true" ',
					'autoplay webkit-playsinline="true" object-fit: fill></video>',
					'<a href="javascript:" onclick="delVidoe()" ><img class="delVideo" src="img/delVideo.png"/></a></div>'].join('');
					$("#videoPlace").append(videoDom);
					layer.close(loadIndex);
				}
				var param = {
					file: file,
					finish: function(result){//上传成功时的回调函数
						console.log(result);
						//记住filedId
						$('#'+index).attr('fileid', result.fileId);
					}
				}
				uploadToVod(param);
			})
		}
	});

	$('#submitpics').on('click', function(){
		$.each($('#picsPlace div'), function(index, elem){
			console.log(elem);
		});
		var loadIndex = layer.load(2);
		//判断是否为空
		var emptity = 0;
		var saveData = {};
		$.each($('.product-info input,textarea'), function(index, elem){
			if(elem.value === '' && elem.name !== 'file'){
				emptity = 1;
				layer.msg(elem.previousElementSibling.textContent + '不能为空');
                return false;
			}else{
                saveData[elem.name] = elem.value;
            }
		});
		if(emptity === 0){
			//取得openId
			var openId = $.cookie("openId");
			var curTiem = new Date().getTime();
			//获取发票文件
			var receiptPath = $('input[name=file]')[0].files[0];
            if (!receiptPath){
                layer.msg("发票不能为空");
                return false;
            }
			//传发票到cos
			var param = {
                file:receiptPath,
                success:function (err, data) {
                    if (err) {
                        console.log(err);
                        return;
                    }
                    if (data.statusCode === 200) {
                        //保存发票名
						saveData.receiptPath = this.Key;
						saveData.openId = openId;
						//联系地址 = 所在地区+详细地址
						saveData.customerAddress = saveData.address + saveData.customerAddress;
						//遍历获取上传的图片和视频
						var image = [];
						$.each($('#picsPlace div'), function(index, elem){
							image.push(elem.title);
						});
						var video = [];
						$.each($('#videoPlace video'), function(index, elem){
							var v = {
								name:elem.title,
								fileId:$(elem).attr('fileid')
							}
							video.push(v);
						});
						//保存图片和视频地址
						saveData.image = image;
						saveData.video = video;
						//获取产品Id
						saveData.productId = $("#showProductPicker").attr('title');
						//该工单的创建人员类型(1:客户/3:维修人员)
						let type = getUrlParam('type');
						//type不为空，则表示是从维修端进入的，新建工单人员为维修人员
						if(type){
							saveData.source = SOURCE_REPAIR;
						}else{
							saveData.source = SOURCE_CUSTOMER;
						}
						Server.postToCustomer('/repair', {repairRecord: JSON.stringify(saveData)}, function(result){
							if(result.code === 200){
								layer.msg("提交成功!");
							}else{
								layer.msg("提交失败！");
							}
							layer.close(loadIndex);
						});
                    }
                },
                curTiem:curTiem
            }
			uploadToCos(param);
		}else{
			layer.close(loadIndex);
		}
	});
	
    //获取短信验证码
    $('#verifyCode').on('click', function (){
        Server.postToCustomer('/getVerifyCode',{phone: $('#phone').val()}, function(result){
            if(result.code == 200){
                layer.msg('验证码发送成功!');
            }else if(result.msg === 'phone_error'){
                layer.msg('请填写正确的手机号码!');
            } else{
                layer.msg('验证码发送失败!');
            }
        });
    });
});

//preload = "metadata";

//删除视频
function delVidoe() {
	console.log('删除');
	console.log($(event.target))
	$(event.target).parent().parent().remove()
}

// 上传视频图片弹出框
$("#uploadpic").click(function () {
	$("#uploadPicVideo").slideToggle();
	mui('#uploadPicVideo').popover('toggle');
});
$("#uploadVideo").click(function () {
	$("#uploadPicVideo").slideToggle();
	mui('#uploadPicVideo').popover('toggle');
});